package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.lang.reflect.Type;
import java.util.List;

/**
 * @Author: bowen
 * @Date: 2019/7/17 15:48
 * @Description:套餐
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

	@Reference
	SetmealService setmealService;

	@Autowired
	JedisPool jedisPool;

	/**
	 * @描述：查询套餐列表
	 */
	@RequestMapping("/getSetmeal")
	public Result findAllSetmeals() {
		try {
			Jedis jedis = jedisPool.getResource();
			String meal = jedis.get("meal");

//			Type type = new TypeReference<List<Setmeal>>() {}.getType();
			List<Setmeal> oldk = JSONArray.parseArray(meal,Setmeal.class);
//			List<Object> list = JSON.parseArray(meal, new Type[]{type});

			if (meal == null) {
				List<Setmeal> setmealList = setmealService.findAllSetmeals();
//				String string = StringUtils.collectionToCommaDelimitedString(setmealList);

				jedis.set("meal", JSON.toJSONString(setmealList));

				return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, setmealList);
			} else {
				return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, oldk);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL);
		}
	}

	/**
	 * @描述:根据套餐ID查询套餐详情（1.套餐的基本信息 2.检查组列表  3.检查项信息）
	 */
	@RequestMapping("/findById")
	public Result findById(Integer id) {
		try {
			Jedis jedis = jedisPool.getResource();
			String meal = jedis.get("setmeal"+id);
//			List<Setmeal> oldk = JSONArray.parseArray(meal,Setmeal.class);
			Setmeal setmeal = JSON.parseObject(meal, Setmeal.class);
			if (meal == null) {
				 setmeal = setmealService.findById(id);
				String string = setmeal.toString();
				jedis.set("setmeal"+setmeal.getId(), string);
				return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
			}else {
				return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
		}
	}
}
